package com.example.demo.service;

import com.example.demo.mdoel.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class RedisService {

    private static final String USER_KEY = "users";

    private final RedisTemplate<String, Object> redisTemplate;
    private HashOperations<String, String, Object> hashOperations;

    @Autowired
    public RedisService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @PostConstruct
    private void init() {
        hashOperations = redisTemplate.opsForHash();
    }

    public void saveUser(User user) {
        hashOperations.put(USER_KEY, user.getUsername(), user);
    }

    public boolean userExists(String username) {
        return hashOperations.hasKey(USER_KEY, username);
    }

    public User getUserByUsername(String username) {
        return (User) hashOperations.get(USER_KEY, username);
    }
}